import hashlib
import base64
import json

from bot.insurance_planner_gpt.qw_server.utils import common_util
from common.log import logger

from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

import settings


class EncodeData:
    def __init__(self, app_key, timestamp, nonce, encoding_content, signature, token, aes_key):
        self.app_key = app_key
        self.token = token
        self.timestamp = timestamp
        self.nonce = nonce
        self.encoding_content = encoding_content
        self.signature = signature
        self.aes_key = aes_key

    @classmethod
    def from_json(cls, json_str):
        json_data = json.loads(json_str)
        app_key = json_data.get('app_key', '')
        company_info = common_util.get_info_by_app_key(common_util.wework_config_list, app_key)
        WE_WORK_CALLBACK_TOKEN = company_info.get("WE_WORK_CALLBACK_TOKEN")
        WE_WORK_ENCODING_AES_KEY = company_info.get("WE_WORK_ENCODING_AES_KEY")
        return cls(
            app_key=app_key,
            timestamp=json_data.get('timestamp', ''),
            nonce=json_data.get('nonce', ''),
            encoding_content=json_data.get('encoding_content', ''),
            signature=json_data.get('signature', ''),
            token=WE_WORK_CALLBACK_TOKEN,
            aes_key=WE_WORK_ENCODING_AES_KEY
        )


class Signature:

    @staticmethod
    def get_signature(encode_data):
        # 加密数据放到列表
        encode_data_list = [encode_data.app_key, encode_data.token, encode_data.nonce, encode_data.timestamp,
                            encode_data.encoding_content]

        # 进行ASCII排序
        encode_data_list.sort()
        # 拼接成字符串
        data_str = "".join(encode_data_list)
        # md5 加密
        md5_hash = hashlib.md5(data_str.encode()).hexdigest()
        return md5_hash

    @staticmethod
    def decode_content(encode_content, aes_key):

        decrypted = ""
        try:
            decoded_content = base64.b64decode(encode_content)
            key = aes_key.encode('utf-8')
            cipher = AES.new(key, AES.MODE_CBC, key[:16])
            decrypted = cipher.decrypt(decoded_content)
            # 去除 PKCS5Padding
            decrypted = unpad(decrypted, 16)
            decrypted = decrypted.decode("utf-8")
        except Exception as e:
            logger.info(f"解密异常:{e}")
        return decrypted

# if __name__ == "__main__":
# aes_key = "6bea83c9f52249ef93f152ff24ff7a2c"
# encode_data = EncodeData(
#     app_key="coc6ad430db858423a",
#     token="803922c7a53e4e0d912456a6f0046e08",
#     timestamp="1651219808",
#     signature="9f79951e7860e52313f7b1ce44842a06",
#     nonce="0b53de9a3ac744d89942eaf7099c8671",
#     encoding_content="SBfeSYG5wornoyUEUtM1iBXaKhJQdoPwPn/XZVRCfoAkodwj3ywYC3PHBoFo4jyhqPXpi2tupocH8f9liFMwwlGhOCjcwGp9X1P1Seoqfwa+OPoDHt6QxwPogQ93ssRquME0RJZfvmG86bf+JCzvy7V0Dq0grDrlTDOwLDF0y8ElWnCyikQzKXjDlcp/RhkL5mvdNL90eJlU3cvYgpOLCh+Ay82YkT6q4pJb8ACOS9S8xvnJbnJdp5D9eIR/Ate1MvEW4XSiHNt5nsNDIb79mHlvz8Jt9Tk8bOy5ZOWwk3JscMFDt/H2N2ZBpaklgp1yxIhqH4/+R9AUUmz0UofuyA=="
# )
# print(Signature.decode_content(encode_data.encoding_content, aes_key))
